<?php defined('SYSPATH') or die('No direct script access.');

require_once Kohana::find_file('classes', 'util');

// URL: /<context>/index.php/Home/
class Controller_Domain extends Controller_Base 
{
	const MODULE_NAME = 'Domain';
	
	private $categoryService;
	
	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);
		
		$this->categoryService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_CATEGORY.'/', ACCESS_TOKEN);
		$this->categoryService->init($this->_requestContext);
	}
	
	private function loadDefaultContent(&$template)
	{
		$this->template->set_global("enableProjectNavBar", false);
	}
	
	public function before()
	{
		parent::before();
		$this->loadDefaultContent($this->template);
		$this->template->set_global('isDomainAdmin', true);
	}
	
	public function action_index()
	{
		$contentFrame = $this->index('Seednia::Project', null, 'default_sbar_left');
		$content = $this->createView('domain_content');
		$contentFrame->content = $content;

		$this->template->scripts = array('public/js/home.js');

		try {
			$this->loadDefaultContent($this->template);

			$cateCriteria = array('kind' => 'Post');
			$ref_categories = $this->categoryService->getList($cateCriteria, 0, 10);
			$content->ref_categories = Util_Data::toMapptingArray($ref_categories, 'sid', 'name');

			$criteria = array('domainId' => $this->_requestContext->domainId);
			// TODO: set privacyLevel
			$content->domainProjects = $this->_projectHelper->getProjectService()->getList($criteria, 0, 10);
			
			$memberCriteria = array('domainSid' => $this->_requestContext->domain->sid);
			$content->domainMembers = $this->domainService->getList($memberCriteria, 0, 20, 'member');

		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add action_index: ' . $ex->getMessage());
		}

	}

	public function action_add()
	{
		if ($this->request->method() == "GET") {
			$this->showForm(true);
		} else if ($this->request->method() == "POST") {
			$this->doAdd();
		}
	}
	
	public function action_edit()
	{
		if ($this->request->method() == "GET") {
			$this->showForm(false);
		} else if ($this->request->method() == "POST") {
			$this->doUpdate();
		}
	}
	
	private function showForm($isNew)
	{
		$title = "Seednia::New ".'MODULE_NAME';
		if (!$isNew) {
			$title = "Seednia::". 'MODULE_NAME' . ' ' .$this->_requestContext->domain->name;
		}
		$contentFrame = $this->loadViews($title, '_default_', null, 'default_sbar_left');		
		$content = $this->createView('domain_form');
		$contentFrame->content = $content;
		
		$cateCriteria = array('kind' => 'Project');
		$ref_categories = $this->categoryService->getList($cateCriteria, 0, 10);
		$content->ref_categories = Util_Data::toMapptingArray($ref_categories, 'sid', 'name');
	}
	
	private function doAdd()
	{
		try {
			$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Home';
			
			$record = $this->loadFormParams();
			$record['creatorSid'] = $this->_sessionInfo->userInfo['userSid'];
			$sid = $this->domainService->add($record);
			
			if ($sid != null) {
				; // TODO: handle error
			}

			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	private function doUpdate()
	{
		try {
			$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Domain';
			
			$record = $this->loadFormParams();
			$this->domainService->update($record);

			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	
	public function action_updateimage()
	{
		if (!$this->isMethodPost())
			return;
			
		try {
			$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Domain';

			$mediaRecord = $this->_resourceHelper->saveFileResource($this->_requestContext, 'profileImage', 'media');
			$this->domainService->update($mediaRecord, $this->_requestContext->domain->sid.'/image/profile');

			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	private function loadFormParams()
	{
		require_once Kohana::find_file('classes', 'util');
		$record = array();
		
		$record['sid'] = $this->request->post('sid');
		$record['id'] = $this->request->post('id');
		//$record['categorySid'] = $this->request->post('categorySid');
		$record['name'] = $this->request->post('name');
		$record['intro'] = $this->request->post('intro');
		$record['description'] = $this->request->post('description');
		$record['status'] = $this->request->post('status');
		$record['tagNamesCsv'] = $this->request->post('tagNamesCsv');

		return $record;
	}
	
	////////// Members //////////
	
	public function action_showmembers()
	{
		$contentFrame = $this->index('Seednia::Project Members');
		$content = $this->createView('project_members');
		$contentFrame->content = $content;
		
		$this->loadDefaultContent($this->template);
				
		$memberRequests = $this->_projectHelper->loadMemberRequests();
		$content->invited = $memberRequests[0];
		$content->memberRequests = $memberRequests[1];
		
		$invitationCriteria = array('projectSid' => $this->_sessionInfo->currentProjectSid);
		$content->invitedEmails = $this->invitationService->getList($invitationCriteria, 0, 20);

	}
	
	public function action_join()
	{
		if ($this->_sessionInfo->userInfo['userSid'] > 0) {
			$domainMember= array('domainSid' => $this->_requestContext->domain->sid);
			$domainMember['userSid'] = $this->_sessionInfo->userInfo['userSid'];
			$this->domainService->add($domainMember, 'member');
		} else {
			// redirect to user registration
		}
	}

} // End Controller_Home